package com.lianxueda.drawing.controller;

import cn.dev33.satoken.stp.SaLoginConfig;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lianxueda.drawing.common.R;
import com.lianxueda.drawing.domain.dto.AdminFormDTO;
import com.lianxueda.drawing.domain.dto.AdminQueryDTO;
import com.lianxueda.drawing.domain.dto.LoginAdminDTO;
import com.lianxueda.drawing.domain.pojo.Admins;
import com.lianxueda.drawing.domain.vo.PageVO;
import com.lianxueda.drawing.service.AdminsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import java.util.Objects;

/**
 * @author 29264
 */
@RequestMapping("/api/v1/auth")
@Tag(name = "管理员管理模块", description = "管理员管理模块接口")
@RestController
@RequiredArgsConstructor
public class AdminController {

    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private final AdminsService adminsService;


    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户登录接口")
    public SaResult login(@RequestBody @Validated LoginAdminDTO loginAdminDTO,
                          HttpServletRequest request) {

        LambdaQueryWrapper<Admins> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Admins::getUsername, loginAdminDTO.getUsername());
        Admins ad = adminsService.getOne(lqw);


        if (Objects.isNull(ad)) {
            return SaResult.error("用户不存在，请重新输入");
        } else {
            if (!passwordEncoder.matches(loginAdminDTO.getPassword(), ad.getPassword())) {
                return SaResult.error("密码错误,请重新输入");
            } else if (ad.getStatus() == 1) {
                return SaResult.error("账号已被注销,请联系管理员");
            } else {
                StpUtil.login(ad.getId(), SaLoginConfig
                        .setExtra("username", ad.getUsername()));
                System.out.println("Logged in user ID: " + ad.getId() + ", Username: " + ad.getUsername());
                String tokenName = StpUtil.getTokenName();
                String tokenValue = StpUtil.getTokenValue();
                ad.setTokenName(tokenName);
                ad.setToken(tokenValue);
                ad.setPassword(loginAdminDTO.getPassword());

                // 第3步，返回给前端
                return SaResult.data(ad);
            }
        }
    }


    @PostMapping("/Pagelist")
    @Operation(summary = "分页查询管理员")
    public R pageList(@RequestBody AdminQueryDTO adminQueryDTO) {
        PageVO pageVo = adminsService.searchPage(adminQueryDTO);
        return R.suc(pageVo);
    }

    @Operation(summary="新增管理")
    @PostMapping("/add")
    public R addAdmin(@RequestBody AdminFormDTO adminFormDTO){
        if (adminsService.getOne(new LambdaQueryWrapper<Admins>().eq(Admins::getUsername, adminFormDTO.getUsername())) != null) {
            return R.fail("用户名已经存在！");
        } else if (adminsService.getOne(new LambdaQueryWrapper<Admins>().eq(Admins::getPhone, adminFormDTO.getPhone())) != null) {
            return R.fail("手机号已经存在！");
        } else {
            Admins admin = new Admins();
            BeanUtils.copyProperties(adminFormDTO, admin);
            adminsService.save(admin);
            return R.suc("添加成功");
        }
    }


    @Operation(summary="删除管理员")
    @DeleteMapping("/delete")
    public R deleteAdmin(@RequestParam Integer id) {
        if (adminsService.getById(id) == null) {
            return R.fail("管理员不存在！");
        }
        adminsService.removeById(id);
        return R.suc("删除成功！");
    }

    @Operation(summary="修改管理员")
    @PostMapping("/update")
    public R updateAdmin(@RequestBody AdminFormDTO adminFormDTO) {
        if (adminsService.getById(adminFormDTO.getId()) == null) {
            return R.fail("管理员不存在！");
        } else {
            //修改
            if (StrUtil.isNotBlank(adminFormDTO.getPassword())) {
                Admins admin = new Admins();
                BeanUtils.copyProperties(adminFormDTO, admin);
                adminFormDTO.setPassword(passwordEncoder.encode(adminFormDTO.getPassword()));
                adminsService.updateById(admin);
                return R.suc("修改成功！");
            }
        }
        return R.fail("修改失败！");
    }


    //根据id修改管理员状态
    @Operation(summary="修改管理员状态")
    @PostMapping("/updateStatus")
    public R updateStatus(@RequestParam Integer id, @RequestParam Integer status) {
        Admins admin = adminsService.getById(id);
        if (admin == null) {
            return R.fail("管理员不存在！");
        } else {
            admin.setStatus(status);
            adminsService.updateById(admin);
            return R.suc("修改成功！");
        }
    }
}



